package com.linkage.blazedsremoting.config;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import javax.ejb.EJBException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.linkage.richers.base.BaseConstant;
import com.linkage.richers.base.BusinessException;
import com.linkage.richers.base.RicherConfig;

import flex.messaging.FlexContext;
import flex.messaging.FlexSession;

public class RBlaze {
    private static final Logger logger = LoggerFactory.getLogger(RBlaze.class
            .getName());
    public static String MOCKSERVICE_FULLNAME = "com.linkage.richers.base.MockService";

    public static Object aroundMethodInvoke(Method method, Object instance,
            Object[] params, String className, String methodName)
            throws IllegalArgumentException, IllegalAccessException,
            InvocationTargetException {

        long start = 0;
        String tokenKey = null;
        FlexSession fSession = FlexContext.getFlexSession();
        Object sessionUser = fSession.getAttribute(BaseConstant.SESSION_USER);

        // 验证登录
        if (RicherConfig.SESSION_ENABLED && sessionUser == null) {

            StringBuffer errorSb = new StringBuffer("非法访问--");
            errorSb.append("sessionId:").append(fSession.getId());

            logger.error(errorSb.toString());
            throw new EJBException(BaseConstant.SESSION_TIME_OUT);

        }

        // 上电文

        if (logger.isDebugEnabled()) {

            start = System.currentTimeMillis();
            tokenKey = className + "::" + methodName;
            StringBuffer upLog = new StringBuffer("请求--");
            upLog.append("Session信息：").append(sessionUser).append("--");
            upLog.append("目标：").append(tokenKey).append("--");

            if (params != null && params.length > 0) {
                upLog.append("参数：");
                for (int i = 0; i < params.length; i++) {
                    upLog.append("[").append(i).append("]").append(params[i]);
                }
            }

            logger.debug(upLog.toString());
        }

        Object rv = null;
        try {
            //MybatisSessionFactory.getSqlSession();
            rv = method.invoke(instance, params);
            return rv;
        } catch (Throwable tra) {
            Throwable cause = tra.getCause();

            if (cause instanceof BusinessException) {
                BusinessException e = (BusinessException) cause;
                String errorCode = e.getMessage();
                StringBuffer errorRV = new StringBuffer(errorCode);
                // 如果有错误参数，以半角分号分隔添加到错误代码之后
                int len = e.getArgs().length;
                if (len > 0) {
                    for (int i = 0; i < len; i++) {
                        errorRV.append(";").append(e.getArgs()[i]);
                    }
                }
                StringBuffer errorSb = new StringBuffer("业务错误--");
                errorSb.append("sessionId:").append(fSession.getId())
                        .append("--");

                errorSb.append("session信息:").append(sessionUser).append("--");
                errorSb.append("错误代码:").append(errorCode);
                logger.error(errorSb.toString());
                throw new EJBException(errorRV.toString());
            } else {

                StringBuffer errorSb = new StringBuffer("系统错误--");
                errorSb.append("sessionId:").append(fSession.getId())
                        .append("--");

                errorSb.append("session信息:").append(sessionUser).append("--");
                errorSb.append("error信息:").append(cause.getMessage());
                logger.error(errorSb.toString(), tra);

                throw new EJBException(BaseConstant.SYSTEM_ERROR);
            }

        } finally {
            //MybatisSessionFactory.closeSqlSession();
            if (logger.isDebugEnabled()) {

                long time = System.currentTimeMillis() - start;
                // 下电文
                StringBuffer downLog = new StringBuffer("应答--");
                downLog.append("Session信息：").append(sessionUser).append("--");
                downLog.append("目标：").append(tokenKey).append("--");
                downLog.append("返回：").append(rv).append("--");
                downLog.append("处理时间：").append(time);

                logger.debug(downLog.toString());
            }

        }

    }
}
